﻿// ----------------------------------------------------------------------
// <author name="Moses Kehengu"/>
// <copyright file="FacilityDetailsForm.cs" company="Futures Group International">
//     Copyright statement. All right reserved
// </copyright>
//
// ------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using GenericTools;
using System.Data.Common;
using System.Data.OleDb;
using ReportingManagement.Components;
using GenericTools.Models;
using DataModels.Enumerations;
using DataModels.Common;

namespace ReportingManagement
{
    /// <summary>
    /// Form that encapsulates the Facility details. Insert, Update and Delete of the facility can be done in this class.
    /// </summary>
    public partial class FacilityDetailsForm : Form
    {
        #region Constants
        private const string FIELD_NOT_APPLICABLE = "NOT APPLICABLE";
        #endregion

        #region Class Constants
        private const string ANC = "ANC";
        private const string PCR = "PCR";
        private const string MAT = "MAT";
        private const string MC = "MC";
        #endregion

        #region Class Variables
        private Facility facility = null;
        private string facilityCode = null;
        private bool canEdit = false;

        private bool deleted = false;
        private bool updated = false;
        private bool added = true;

        private UserInformation user;
        #endregion

        #region Constructors
        public FacilityDetailsForm(UserInformation user)
        {
            InitializeComponent();
            this.user = user;

            // Populating list of regions
            Cursor.Current = Cursors.WaitCursor;
            DataTable dataTable = null;
            if (this.user.Level == AccessLevel.ADMINISTRATOR)
            {
                dataTable = Utilities.GetAllRegions();
            }
            else
            {
                dataTable = Utilities.GetAllRegions(this.user.SupportingPartnerId);
            }
            Cursor.Current = Cursors.Default;
            RegionComboBox.DisplayMember = "RegionName";
            RegionComboBox.ValueMember = "RegionID";
            RegionComboBox.DataSource = dataTable;

            dataTable = Utilities.GetFacilityTypes();
            cboFacilityType.DisplayMember = "TypeName";
            cboFacilityType.ValueMember = "TypeId";
            cboFacilityType.DataSource = dataTable;

            try
            {
                int regionID = int.Parse(RegionComboBox.SelectedValue.ToString());
                Cursor.Current = Cursors.WaitCursor;
                if (this.user.Level == AccessLevel.ADMINISTRATOR)
                {
                    dataTable = Utilities.GetDistrictsByRegion(regionID);
                }
                else
                {
                    dataTable = Utilities.GetDistrictsByRegion(regionID, this.user.SupportingPartnerId);
                }
                Cursor.Current = Cursors.Default;
                DistrictComboBox.DataSource = dataTable;
                DistrictComboBox.ValueMember = "DistrictNo";
                DistrictComboBox.DisplayMember = "District";
            }
            catch { }

            // Populating list of expected reports
            Cursor.Current = Cursors.WaitCursor;
            dataTable = Utilities.GetAllExpectedReports();
            Cursor.Current = Cursors.Default;
            foreach (DataRow row in dataTable.Rows)
            {
                ListItem item = new ListItem();
                item.Text = row[1].ToString();
                item.Value = int.Parse(row[0].ToString());
                ReportsCheckedListBox.Items.Add(item);
            }

            // Populating Supporting Partners
            Cursor.Current = Cursors.WaitCursor;
            dataTable = Utilities.GetSupportingPartner();
            Cursor.Current = Cursors.Default;
            cboSupportingPartner.ValueMember = "Id";
            cboSupportingPartner.DisplayMember = "Name";
            cboSupportingPartner.DataSource = dataTable;
            if (this.user.Level != AccessLevel.ADMINISTRATOR)
            {
                cboSupportingPartner.SelectedValue = this.user.SupportingPartnerId;
                cboSupportingPartner.Enabled = false;
            }

            // Getting facility details
            facility = new Facility(this.user.ID);
            this.Text = "Facility Details - New Facility";
            DeleteButton.Enabled = facility.CanBeDeleted;
            btnReset.Enabled = false;
            btnShowRegisteredUsers.Enabled = false;
        }

        public FacilityDetailsForm(string facilityCode, bool canEdit, UserInformation user)
        {
            InitializeComponent();
            this.user = user;

            this.facilityCode = facilityCode;
            this.canEdit = canEdit;
            this.added = false;

            // Populating list of regions
            Cursor.Current = Cursors.WaitCursor;
            DataTable dataTable = null;
            if (this.user.Level == AccessLevel.ADMINISTRATOR)
            {
                dataTable = Utilities.GetAllRegions();
            }
            else
            {
                dataTable = Utilities.GetAllRegions(this.user.SupportingPartnerId);
            }
            Cursor.Current = Cursors.Default;
            RegionComboBox.DisplayMember = "RegionName";
            RegionComboBox.ValueMember = "RegionID";
            RegionComboBox.DataSource = dataTable;

            dataTable = Utilities.GetFacilityTypes();
            cboFacilityType.DisplayMember = "TypeName";
            cboFacilityType.ValueMember = "TypeId";
            cboFacilityType.DataSource = dataTable;

            try
            {
                int regionID = int.Parse(RegionComboBox.SelectedValue.ToString());
                Cursor.Current = Cursors.WaitCursor;
                if (this.user.Level == AccessLevel.ADMINISTRATOR)
                {
                    dataTable = Utilities.GetDistrictsByRegion(regionID);
                }
                else
                {
                    dataTable = Utilities.GetDistrictsByRegion(regionID, this.user.SupportingPartnerId);
                }
                Cursor.Current = Cursors.Default;
                DistrictComboBox.ValueMember = "DistrictNo";
                DistrictComboBox.DisplayMember = "District";
                DistrictComboBox.DataSource = dataTable;
            }
            catch { }

            // Populating supporting partners
            Cursor.Current = Cursors.WaitCursor;
            dataTable = Utilities.GetSupportingPartner();
            Cursor.Current = Cursors.Default;
            cboSupportingPartner.ValueMember = "Id";
            cboSupportingPartner.DisplayMember = "Name";
            cboSupportingPartner.DataSource = dataTable;
            if (this.user.Level != AccessLevel.ADMINISTRATOR)
            {
                cboSupportingPartner.SelectedValue = this.user.SupportingPartnerId;
                cboSupportingPartner.Enabled = false;
            }

            // Populating list of expected reports
            Cursor.Current = Cursors.WaitCursor;
            dataTable = Utilities.GetAllExpectedReports();
            Cursor.Current = Cursors.Default;
            foreach (DataRow row in dataTable.Rows)
            {
                ListItem item = new ListItem();
                item.Text = row[1].ToString();
                item.Value = int.Parse(row[0].ToString());
                ReportsCheckedListBox.Items.Add(item);
            }

            DataTable expectedReportTable = dataTable.Copy();
            DataColumn c = new DataColumn("ReportStatus", Type.GetType("System.Boolean"));
            expectedReportTable.Columns.Add(c);
            foreach (DataRow r in expectedReportTable.Rows) r["ReportStatus"] = true;
            
            PopulateFacilityDetails();
        }
        #endregion

        #region Event Handlers
        private void RegionComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int regionID = int.Parse(RegionComboBox.SelectedValue.ToString());
                Cursor.Current = Cursors.WaitCursor;
                DataTable dataTable = null;
                if (this.user.Level == AccessLevel.ADMINISTRATOR)
                {
                    dataTable = Utilities.GetDistrictsByRegion(regionID);
                }
                else
                {
                    dataTable = Utilities.GetDistrictsByRegion(regionID, this.user.SupportingPartnerId);
                }
                Cursor.Current = Cursors.Default;
                DistrictComboBox.DataSource = dataTable;
                DistrictComboBox.ValueMember = "DistrictNo";
                DistrictComboBox.DisplayMember = "District";
            }
            catch { }
        }

        private void SaveChangesButton_Click(object sender, EventArgs e)
        {
            // Since internal name is no longer edited through this form.
            // This line is here for backward compatibility with exisiting
            // form validation logic.
            txtInternalName.Text = FIELD_NOT_APPLICABLE;
            FacilityShortnameTextBox.Text = FIELD_NOT_APPLICABLE;
            
            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                string message = @"The application is running in offline mode. " +
                    "You can not perform any activities that require server " +
                    "connection while you are offline. " +
                    "\n\nYou are current operation will not be processed!";
                MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            SaveChangesButton.Enabled = false;
            Application.DoEvents();
            bool okToContinue = ValidateForm();

            if (okToContinue)
            {
                this.facility.Code = FacilityCodeTextBox.Text;
                this.facility.Name = FacilityFullnameTextBox.Text;
                this.facility.ShortName = FacilityShortnameTextBox.Text;
                this.facility.InternalName = txtInternalName.Text;
                this.facility.Description = FacilityDescriptionTextBox.Text;
                this.facility.RegionID = int.Parse(RegionComboBox.SelectedValue.ToString());
                this.facility.DistrictID = int.Parse(DistrictComboBox.SelectedValue.ToString());
                this.facility.Address = FacilityAddressTextBox.Text;
                this.facility.PrincipalContact = FacilityContactTextBox.Text;

                if (ActiveRadioButton.Checked)
                {
                    this.facility.Actived = true;
                    this.facility.ActivityDate = ActivityDateTimePicker.Value;
                }
                if (InactiveRadioButton.Checked)
                {
                    this.facility.Actived = false;
                    this.facility.ActivityDate = ActivityDateTimePicker.Value;
                }
                this.facility.Remarks = FacilityNotesTextBox.Text;

                this.facility.ProvideANC = ANCCheckBox.Checked;
                this.facility.ANCStartDate = ANCDateTimePicker.Value;

                this.facility.ProvideLD = LDCheckBox.Checked;
                this.facility.LDStartDate = LDDateTimePicker.Value;

                this.facility.ProvideHEID = HEIDCheckBox.Checked;
                this.facility.HEIDStartDate = HEIDDateTimePicker.Value;

                this.facility.ProvideProphylaxis = ProphylCheckBox.Checked;
                this.facility.ProphylaxisStartDate = ProphylDateTimePicker.Value;

                // Remove previous set expected reports and set the new one based on the selection.
                this.facility.ExpectedReports.Clear();
                foreach (ListItem i in ReportsCheckedListBox.CheckedItems)
                {
                    int r = int.Parse(i.Value.ToString());
                    DataRow row = this.facility.ExpectedReports.NewRow();
                    row["ReportId"] = r;
                    row["ReportingStartDate"] = DateTime.Now;
                    row["DirectEntry"] = true;
                    this.facility.ExpectedReports.Rows.Add(row);
                    //this.facility.ExpectedReports[r] = DateTime.Now;
                }

                OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.CacheSettingConnection);
                connection.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = connection;
                command.CommandText = "SELECT * FROM ReportAssociation";
                DataTable dataTable = GenericDataAccess.ExecuteSelectCommand(command);

                foreach (DataRow r in dataTable.Rows)
                {
                    string name = r["ReportName"].ToString();
                    string associatedReportIds = r["AssociatedReportIds"].ToString();
                    string[] ids = associatedReportIds.Split('|');
                    int reportViewId = Int32.Parse(r["ReportViewId"].ToString());

                    // This is required to make the main report is included as one of the expected report
                    bool mainReportFound = false;
                    foreach (DataRow er in this.facility.ExpectedReports.Rows)
                    {
                        int reportId = Int32.Parse(er["ReportId"].ToString());
                        if (reportId == reportViewId)
                        {
                            mainReportFound = true;
                            break;
                        }
                    }
                    //foreach (int id in this.facility.ExpectedReports.Keys)
                    //{
                    //    if (id == reportViewId)
                    //    {
                    //        mainReportFound = true;
                    //        break;
                    //    }
                    //}

                    foreach (string id in ids)
                    {
                        int ID = Int32.Parse(id);
                        List<DataRow> expectedReportsToBeAdded = new List<DataRow>();
                        foreach (DataRow er in this.facility.ExpectedReports.Rows)
                        {
                            int reportId = Int32.Parse(er["ReportId"].ToString());
                            if (reportId == ID)
                            {
                                switch (name)
                                {
                                    case ANC:
                                        er["ReportingStartDate"] = ANCDateTimePicker.Value;
                                        //this.facility.ExpectedReports[ID] = ANCDateTimePicker.Value;
                                        if (!mainReportFound)
                                        {
                                            //this.facility.ExpectedReports[reportViewId] = ANCDateTimePicker.Value;
                                            DataRow row = this.facility.ExpectedReports.NewRow();
                                            row["ReportId"] = reportViewId;
                                            row["ReportingStartDate"] = ANCDateTimePicker.Value;
                                            row["DirectEntry"] = false; // Not meant to entered using SMS
                                            //this.facility.ExpectedReports.Rows.Add(row);
                                            expectedReportsToBeAdded.Add(row);
                                            mainReportFound = true;
                                        }
                                        break;

                                    case PCR:
                                        er["ReportingStartDate"] = ProphylDateTimePicker.Value;
                                        //this.facility.ExpectedReports[ID] = ProphylDateTimePicker.Value;
                                        if (!mainReportFound)
                                        {
                                            //this.facility.ExpectedReports[reportViewId] = ProphylDateTimePicker.Value;
                                            DataRow row = this.facility.ExpectedReports.NewRow();
                                            row["ReportId"] = reportViewId;
                                            row["ReportingStartDate"] = ProphylDateTimePicker.Value;
                                            row["DirectEntry"] = false; // Not meant to entered using SMS
                                            //this.facility.ExpectedReports.Rows.Add(row);
                                            expectedReportsToBeAdded.Add(row);
                                            mainReportFound = true;
                                        }
                                        break;

                                    case MAT:
                                        er["ReportingStartDate"] = LDDateTimePicker.Value;
                                        //this.facility.ExpectedReports[ID] = LDDateTimePicker.Value;
                                        if (!mainReportFound)
                                        {
                                            //this.facility.ExpectedReports[reportViewId] = LDDateTimePicker.Value;
                                            DataRow row = this.facility.ExpectedReports.NewRow();
                                            row["ReportId"] = reportViewId;
                                            row["ReportingStartDate"] = LDDateTimePicker.Value;
                                            row["DirectEntry"] = false; // Not meant to entered using SMS
                                            //this.facility.ExpectedReports.Rows.Add(row);
                                            expectedReportsToBeAdded.Add(row);
                                            mainReportFound = true;
                                        }
                                        break;

                                    case MC:
                                        er["ReportingStartDate"] = HEIDDateTimePicker.Value;
                                        //this.facility.ExpectedReports[ID] = HEIDDateTimePicker.Value;
                                        if (!mainReportFound)
                                        {
                                            //this.facility.ExpectedReports[reportViewId] = HEIDDateTimePicker.Value;
                                            DataRow row = this.facility.ExpectedReports.NewRow();
                                            row["ReportId"] = reportViewId;
                                            row["ReportingStartDate"] = HEIDDateTimePicker.Value;
                                            row["DirectEntry"] = false; // Not meant to entered using SMS
                                            //this.facility.ExpectedReports.Rows.Add(row);
                                            expectedReportsToBeAdded.Add(row);
                                            mainReportFound = true;
                                        }
                                        break;
                                }
                            }
                        }
                        foreach (DataRow extras in expectedReportsToBeAdded) this.facility.ExpectedReports.Rows.Add(extras);

                        //if (this.facility.ExpectedReports.ContainsKey(ID))
                        //{
                        //    switch (name)
                        //    {
                        //        case ANC:
                        //            this.facility.ExpectedReports[ID] = ANCDateTimePicker.Value;
                        //            if (!mainReportFound)
                        //            {
                        //                this.facility.ExpectedReports[reportViewId] = ANCDateTimePicker.Value;
                        //                mainReportFound = true;
                        //            }
                        //            break;

                        //        case PCR:
                        //            this.facility.ExpectedReports[ID] = ProphylDateTimePicker.Value;
                        //            if (!mainReportFound)
                        //            {
                        //                this.facility.ExpectedReports[reportViewId] = ProphylDateTimePicker.Value;
                        //                mainReportFound = true;
                        //            }
                        //            break;

                        //        case MAT:
                        //            this.facility.ExpectedReports[ID] = LDDateTimePicker.Value;
                        //            if (!mainReportFound)
                        //            {
                        //                this.facility.ExpectedReports[reportViewId] = LDDateTimePicker.Value;
                        //                mainReportFound = true;
                        //            }
                        //            break;

                        //        case MC:
                        //            this.facility.ExpectedReports[ID] = HEIDDateTimePicker.Value;
                        //            if (!mainReportFound)
                        //            {
                        //                this.facility.ExpectedReports[reportViewId] = HEIDDateTimePicker.Value;
                        //                mainReportFound = true;
                        //            }
                        //            break;
                        //    }
                        //}
                    }
                }

                this.facility.Trained = chkTrained.Checked;
                this.facility.ProvideDBS = chkProvideDBS.Checked;
                this.facility.FacilityType = Int32.Parse(cboFacilityType.SelectedValue.ToString());
                this.facility.SupportingPartnerId = Int32.Parse(cboSupportingPartner.SelectedValue.ToString());

                Cursor.Current = Cursors.WaitCursor;
                bool saved = this.facility.Save();
                Cursor.Current = Cursors.Default;
                if (saved)
                {
                    MessageBox.Show(this, "Facility changes were saved successfully", "Facility Details",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.updated = true;
                    this.facilityCode = this.facility.Code;
                }
                SaveChangesButton.Enabled = true;
                DialogResult = System.Windows.Forms.DialogResult.OK;
                this.updated = true;
            }
            else
            {
                SaveChangesButton.Enabled = true;
                return;
            }            
        }

        private void DeleteButton_Click(object sender, EventArgs e)
        {
            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                string message = @"The application is running in offline mode. " +
                    "You can not perform any activities that require server " +
                    "connection while you are offline. " +
                    "\n\nYou are current operation will not be processed!";
                MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            DialogResult response = MessageBox.Show(this,
                String.Format("Are you sure you want to delete {0} with facility code: {1}?", 
                this.facility.Name, this.facility.OriginalCode), "Confirm Delete", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (response == DialogResult.Yes)
            {
                Cursor.Current = Cursors.WaitCursor;
                bool success = Facility.Delete(this.facility.OriginalCode, this.user.ID);
                Cursor.Current = Cursors.Default;
                if (success)
                {
                    DialogResult = System.Windows.Forms.DialogResult.OK;
                    this.deleted = true;
                    this.Close();
                }
            }
        }

        private void ANCCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            bool state = ANCCheckBox.Checked;
            ANCStartDateLabel.Enabled = state;
            ANCDateTimePicker.Enabled = state;
        }

        private void LDCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            bool state = LDCheckBox.Checked;
            LDStartDateLabel.Enabled = state;
            LDDateTimePicker.Enabled = state;
        }

        private void HEIDCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            bool state = HEIDCheckBox.Checked;
            HEIDStartDateLabel.Enabled = state;
            HEIDDateTimePicker.Enabled = state;
        }

        private void ProphylCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            bool state = ProphylCheckBox.Checked;
            ProphylStartDateLabel.Enabled = state;
            ProphylDateTimePicker.Enabled = state;
        }

        private void ActiveRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            if (ActiveRadioButton.Checked)
            {
                lblActivityDate.Text = "Active Date";
                ActivityDateTimePicker.Value = facility.ActivityDate;
            }
        }

        private void InactiveRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            if (InactiveRadioButton.Checked)
            {
                lblActivityDate.Text = "Inactive Date";
                ActivityDateTimePicker.Value = facility.ActivityDate;
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            btnReset.Enabled = false;
            bool saveState = SaveChangesButton.Enabled;
            SaveChangesButton.Enabled = false;
            Cursor.Current = Cursors.WaitCursor;
            Application.DoEvents();
            PopulateFacilityDetails();
            SaveChangesButton.Enabled = saveState;
            btnReset.Enabled = true;
        }

        private void btnShowRegisteredUsers_Click(object sender, EventArgs e)
        {
            FacilityRegisteredUsers facilityRegisteredUsers = new FacilityRegisteredUsers(facilityCode);
            facilityRegisteredUsers.ShowDialog(this);
        }
        #endregion

        #region Helper Methods
        private bool ValidateForm()
        {
            #region Checking Empty Fields
            if (String.IsNullOrEmpty(FacilityCodeTextBox.Text))
            {
                MessageBox.Show(this, "Facility code can not be empty. Please provide valid facility code",
                    "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                FacilityCodeTextBox.Focus();
                return false;
            }

            if (String.IsNullOrEmpty(FacilityFullnameTextBox.Text))
            {
                MessageBox.Show(this, "Facility full name can not be empty. Please provide valid facility full name",
                    "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                FacilityFullnameTextBox.Focus();
                return false;
            }

            if (String.IsNullOrEmpty(txtInternalName.Text))
            {
                MessageBox.Show(this, 
                    "Facility internal name can not be empty. It is useful during reporting. Please provide valid facility full name",
                    "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                FacilityFullnameTextBox.Focus();
                return false;
            }

            if (String.IsNullOrEmpty(FacilityShortnameTextBox.Text))
            {
                MessageBox.Show(this, "Facility short name can not be empty. Please provide valid facility short name",
                    "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                FacilityShortnameTextBox.Focus();
                return false;
            }

            if (ReportsCheckedListBox.CheckedItems.Count < 1)
            {
                MessageBox.Show(this, "Please select at least one report for this facility", "Input Error", 
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                ReportsCheckedListBox.Focus();
                return false;
            }
            #endregion

            #region Checking Report and Services Appropriateness
            #region Preparing Checking Variables
            OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.CacheSettingConnection);
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            command.CommandText = "SELECT * FROM ReportAssociation";
            DataTable dataTable = GenericDataAccess.ExecuteSelectCommand(command);

            List<int> anc = new List<int>();
            List<int> pcr = new List<int>();
            List<int> mat = new List<int>();
            List<int> mc = new List<int>();

            int ancReportViewId = -1;
            int pcrReportViewId = -1;
            int matReportViewId = -1;
            int mcReportViewId = -1;

            foreach (DataRow r in dataTable.Rows)
            {
                string name = r["ReportName"].ToString();
                string associatedReportIds = r["AssociatedReportIds"].ToString();
                string[] ids = associatedReportIds.Split('|');
                //int reportViewId = Int32.Parse(r["ReportViewId"].ToString());
                
                // These are for automatic checking the report views if not checked
                //if (name == ANC) ancReportViewId = reportViewId;
                //if (name == PCR) pcrReportViewId = reportViewId;
                //if (name == MAT) matReportViewId = reportViewId;
                //if (name == MC) mcReportViewId = reportViewId;
                
                foreach (string id in ids)
                {
                    int ID = Int32.Parse(id);
                    if (name == ANC) anc.Add(ID);
                    if (name == PCR) pcr.Add(ID);
                    if (name == MAT) mat.Add(ID);
                    if (name == MC) mc.Add(ID);
                }
            }

            List<int> selectedReports = new List<int>();
            foreach (ListItem i in ReportsCheckedListBox.CheckedItems)
            {
                int r = int.Parse(i.Value.ToString());
                selectedReports.Add(r);
            }

            bool foundANCReport = false;
            foreach (int r in anc)  // Going through all ANC reports
            {
                foreach (int s in selectedReports)  // We just need to find atleast one among selected
                {
                    if (r == s)
                    {
                        foundANCReport = true;
                        break;
                    }
                }
                if (foundANCReport) break;
            }

            bool foundPCRReport = false;
            foreach (int r in pcr)  // Going through all PCR reports
            {
                foreach (int s in selectedReports)  // We just need to find atleast one among selected
                {
                    if (r == s)
                    {
                        foundPCRReport = true;
                        break;
                    }
                }
                if (foundPCRReport) break;
            }

            bool foundMATReport = false;
            foreach (int r in mat)  // Going through all ANC reports
            {
                foreach (int s in selectedReports)  // We just need to find atleast one among selected
                {
                    if (r == s)
                    {
                        foundMATReport = true;
                        break;
                    }
                }
                if (foundMATReport) break;
            }

            bool foundMCReport = false;
            foreach (int r in mc)  // Going through all ANC reports
            {
                foreach (int s in selectedReports)  // We just need to find atleast one among selected
                {
                    if (r == s)
                    {
                        foundMCReport = true;
                        break;
                    }
                }
                if (foundMCReport) break;
            }
            #endregion

            // Checking appropriate ANC reports
            #region Checking ANC Reports
            if (ANCCheckBox.Checked)
            {
                if (!foundANCReport)
                //{
                //    // Going through each checked report to make sure the main view is included
                //    bool alreadyChecked = false;
                //    foreach (ListItem i in ReportsCheckedListBox.CheckedItems)
                //    {
                //        int r = int.Parse(i.Value.ToString());
                //        if (r == ancReportViewId)
                //        {
                //            alreadyChecked = true;
                //            break;
                //        }
                //    }
                //    if (!alreadyChecked) selectedReports.Add(ancReportViewId);
                //}
                //else
                {
                    MessageBox.Show(this, 
                        @"You have selected PMTCT Antenatal Clinic (ANC) Services but you have not selected at least one of its associated reports. Please select appropriate report(s).",
                        String.Format("{0} - Input Error", AppConfiguration.ApplicationName), MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    ReportsCheckedListBox.Focus();
                    return false;
                }
            }
            else
            {
                if (foundANCReport)
                {
                    MessageBox.Show(this,
                        @"You have not selected PMTCT Antenatal Clinic (ANC) Services but you have selected at least one of its associated reports. Please select appropriate report(s).",
                        String.Format("{0} - Input Error", AppConfiguration.ApplicationName), MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    ReportsCheckedListBox.Focus();
                    return false;
                }
            }
            #endregion

            // Checking appropriate PCR reports
            #region Checking PCR Reports
            if (ProphylCheckBox.Checked)
            {
                if (!foundPCRReport)
                {
                    MessageBox.Show(this,
                        @"You have selected PMTCT Care Services but you have not selected at least one of its associated reports. Please select appropriate report(s).",
                        String.Format("{0} - Input Error", AppConfiguration.ApplicationName), MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    ReportsCheckedListBox.Focus();
                    return false;
                }
            }
            else
            {
                if (foundPCRReport)
                {
                    MessageBox.Show(this,
                        @"You have not selected PMTCT Care Services but you have selected at least one of its associated reports. Please select appropriate report(s).",
                        String.Format("{0} - Input Error", AppConfiguration.ApplicationName), MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    ReportsCheckedListBox.Focus();
                    return false;
                }
            }
            #endregion

            // Checking appropriate MAT reports
            #region Checking MAT Reports
            if (LDCheckBox.Checked)
            {
                if (!foundMATReport)
                {
                    MessageBox.Show(this,
                        @"You have selected PMTCT Maternity (L&D) Services but you have not selected at least one of its associated reports. Please select appropriate report(s).",
                        String.Format("{0} - Input Error", AppConfiguration.ApplicationName), MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    ReportsCheckedListBox.Focus();
                    return false;
                }
            }
            else
            {
                if (foundMATReport)
                {
                    MessageBox.Show(this,
                        @"You have not selected PMTCT Maternity (L&D) Services but you have selected at least one of its associated reports. Please select appropriate report(s).",
                        String.Format("{0} - Input Error", AppConfiguration.ApplicationName), MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    ReportsCheckedListBox.Focus();
                    return false;
                }
            }
            #endregion

            // Checking appropriate MC reports
            #region Checking MC Reports
            if (HEIDCheckBox.Checked)
            {
                if (!foundMCReport)
                {
                    MessageBox.Show(this,
                        @"You have selected PMTCT Mother Child Follow-Up Services but you have not selected at least one of its associated reports. Please select appropriate report(s).",
                        String.Format("{0} - Input Error", AppConfiguration.ApplicationName), MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    ReportsCheckedListBox.Focus();
                    return false;
                }
            }
            else
            {
                if (foundMCReport)
                {
                    MessageBox.Show(this,
                        @"You have not selected PMTCT Mother Child Follow-Up Services but you have selected at least one of its associated reports. Please select appropriate report(s).",
                        String.Format("{0} - Input Error", AppConfiguration.ApplicationName), MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    ReportsCheckedListBox.Focus();
                    return false;
                }
            }
            #endregion
            #endregion

            return true;
        }

        private  void PopulateFacilityDetails()
        {
            // Getting facility details
            facility = new Facility(this.facilityCode, this.user.ID);
            this.Text = String.Format("Facility Details - [{0}] : {1}", facility.OriginalCode, facility.Name);

            FacilityCodeTextBox.Text = facility.Code;
            FacilityFullnameTextBox.Text = facility.Name;
            FacilityShortnameTextBox.Text = facility.ShortName;
            txtInternalName.Text = facility.InternalName;
            FacilityDescriptionTextBox.Text = facility.Description;
            RegionComboBox.SelectedValue = facility.RegionID;
            DistrictComboBox.SelectedValue = facility.DistrictID;
            FacilityAddressTextBox.Text = facility.Address;
            FacilityContactTextBox.Text = facility.PrincipalContact;
            cboFacilityType.SelectedValue = facility.FacilityType;

            cboSupportingPartner.SelectedValue = facility.SupportingPartnerId;

            if (this.facility.Actived)
            {
                ActiveRadioButton.Checked = true;
                lblActivityDate.Text = "Active Date";
                ActivityDateTimePicker.Value = facility.ActivityDate;
            }
            else
            {
                InactiveRadioButton.Checked = true;
                lblActivityDate.Text = "Inactive Date";
                ActivityDateTimePicker.Value = facility.ActivityDate;
            }


            FacilityNotesTextBox.Text = this.facility.Remarks;

            LDCheckBox.Checked = this.facility.ProvideLD;
            LDDateTimePicker.Value = this.facility.LDStartDate;

            //ANCCheckBox.Checked = this.facility.ProvidePMTCT;
            //ANCDateTimePicker.Value = this.facility.PMTCTStartDate;
            ANCCheckBox.Checked = this.facility.ProvideANC;
            ANCDateTimePicker.Value = this.facility.ANCStartDate;

            HEIDCheckBox.Checked = this.facility.ProvideHEID;
            HEIDDateTimePicker.Value = this.facility.HEIDStartDate;

            ProphylCheckBox.Checked = this.facility.ProvideProphylaxis;
            ProphylDateTimePicker.Value = this.facility.ProphylaxisStartDate;

            // Clear all selection
            for (int i = 0; i < ReportsCheckedListBox.Items.Count; i++)
            {
                ReportsCheckedListBox.SetItemChecked(i, false);
            }

            foreach (DataRow row in this.facility.ExpectedReports.Rows)
            {
                int r = Int32.Parse(row["ReportId"].ToString());
                bool directEntry = Boolean.Parse(row["DirectEntry"].ToString());
                for (int i = 0; i < ReportsCheckedListBox.Items.Count; i++)
                {
                    ListItem item = (ListItem)ReportsCheckedListBox.Items[i];
                    int report = int.Parse(item.Value.ToString());
                    if (r == report)
                    {
                        ReportsCheckedListBox.SetItemChecked(i, directEntry);
                        //offset = i + 1;
                        break;
                    }
                }
            }

            //foreach (int r in this.facility.ExpectedReports.Keys)
            //{
            //    for (int i = 0; i < ReportsCheckedListBox.Items.Count; i++)
            //    {
            //        ListItem item = (ListItem)ReportsCheckedListBox.Items[i];
            //        int report = int.Parse(item.Value.ToString());
            //        if (r == report)
            //        {
            //            ReportsCheckedListBox.SetItemChecked(i, true);
            //            //offset = i + 1;
            //            break;
            //        }
            //    }
            //}
            DeleteButton.Enabled = facility.CanBeDeleted;

            if (!this.canEdit)
            {
                DeleteButton.Enabled = false;
                SaveChangesButton.Enabled = false;
            }
            chkTrained.Checked = facility.Trained;
            chkProvideDBS.Checked = facility.ProvideDBS;
        }
        #endregion        

        #region Public Properties
        public bool Updated
        {
            get
            {
                return this.updated;
            }
        }

        public bool Deleted
        {
            get
            {
                return this.deleted;
            }
        }

        public bool Added
        {
            get
            {
                return this.added;
            }
        }

        public string FacilityCode
        {
            get
            {
                return this.facility.Code;
            }
        }

        public string FacilityName
        {
            get
            {
                return FacilityFullnameTextBox.Text;
            }
        }

        public bool Active
        {
            get
            {
                return ActiveRadioButton.Checked;
            }
        }

        public bool Trained
        {
            get
            {
                return chkTrained.Checked;
            }
        }

        public string DistrictName
        {
            get
            {
                return DistrictComboBox.Text;
            }
        }

        public string RegionName
        {
            get
            {
                return RegionComboBox.Text;
            }
        }

        public int SupportingPartnerId
        {
            get
            {
                return this.facility.SupportingPartnerId;
            }
        }

        public string SupportingPartner
        {
            get
            {
                DataRowView rowView = (DataRowView)cboSupportingPartner.SelectedItem;
                string supportingPartner = rowView["Name"].ToString();
                return supportingPartner;
            }
        }
        #endregion        
    }
}
